//
//  YFDayPickerAlertView.m
//  SquashSpark
//
//  Created by Coollang on 2017/12/13.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFDayPickerAlertView.h"
#import "NSDate+FormateString.h"
#import <DateTools/DateTools.h>

@interface YFDayPickerAlertView()<UIPickerViewDelegate,UIPickerViewDataSource>
@property (weak, nonatomic) IBOutlet UIButton *confirmButton;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;

/** 数据源: [2017-12-01] 的日期数组 */
@property (nonatomic, strong) NSArray *daysDataSource;

/** 处理后的日期数据 */
@property (nonatomic, strong) NSDictionary *yearMonthDayDict;

/** 当前选中的年 */
@property (nonatomic, copy) NSString *currentYear;
/** 当前选中的月 */
@property (nonatomic, copy) NSString *currentMonth;
/** 当前选中的天 */
@property (nonatomic, copy) NSString *currentDay;

@property (nonatomic, copy) NSString *defalutDay;

@end

@implementation YFDayPickerAlertView

+ (instancetype)dayPickerAlertView {
    return [[[NSBundle mainBundle] loadNibNamed:@"YFDayPickerAlertView" owner:nil options:nil] firstObject];
}

- (void)configuerWithDays:(NSArray *)days withCurrentDay:(NSString *)currentDay {
    self.daysDataSource = days;
    self.defalutDay = currentDay;
}

- (IBAction)confirmButtonClick:(UIButton *)sender {
    if (self.clickConfirmButtonBlock) {
        NSInteger oneComRow = [self.pickerView selectedRowInComponent:0];
        NSInteger twoComRow = [self.pickerView selectedRowInComponent:1];
        NSInteger threeComRow = [self.pickerView selectedRowInComponent:2];
        NSString *year = [self.yearMonthDayDict.allKeys objectAtIndex:oneComRow];
        NSString *month = [[self.yearMonthDayDict[year] allKeys] objectAtIndex:twoComRow];
        NSString *day = self.yearMonthDayDict[year][month][threeComRow];
        NSDate *selectDay = [NSDate formateYearMonthDayString:[NSString stringWithFormat:@"%@-%@-%@",year,month,day]];
        NSString *selectDayStr = [NSString stringWithFormat:@"%@/%@/%@",year,month,day];
        self.clickConfirmButtonBlock(selectDay,selectDayStr);
    }
}

- (void)configuerDefulatValue {
    if (![self.daysDataSource containsObject:self.defalutDay]) {
        return;
    }
    NSDate *date = [NSDate formateYearMonthDayString:self.defalutDay];
    NSString *year = @([date year]).stringValue;
    NSString *month = @([date month]).stringValue;
    NSString *day = @([date day]).stringValue;
    if ([self.yearMonthDayDict.allKeys containsObject:year]) {
        self.currentYear = @([date year]).stringValue;
        NSInteger oneComRow = [self.yearMonthDayDict.allKeys indexOfObject:year];
        [self.pickerView selectRow:oneComRow inComponent:0 animated:YES];
        [self.pickerView reloadComponent:1];
        [self.pickerView reloadComponent:2];
        NSDictionary *dict = self.yearMonthDayDict[self.currentYear];
        if ([dict.allKeys containsObject:month]) {
            self.currentMonth = month;
            NSInteger twoComRow = [dict.allKeys indexOfObject:self.currentMonth];
            [self.pickerView selectRow:twoComRow inComponent:1 animated:YES];
            [self.pickerView reloadComponent:2];
            if ([dict[month] containsObject:day]) {
                NSInteger threeComRow = [dict[month] indexOfObject:day];
                [self.pickerView selectRow:threeComRow inComponent:2 animated:YES];
            }
        }
    }
}

- (void)awakeFromNib {
    [super awakeFromNib];
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self.confirmButton clipsCornerRadius:3];
    [self clipsCornerRadius:6 borderWidth:1.5 borderColor:kYellowGreenColor];
    // 获取有数据的天
    [self configuerDefulatValue];
}

- (void)setDaysDataSource:(NSArray *)daysDataSource {
    // 日期从小到大排序
    dispatch_async(dispatch_queue_create("SportSelectDayQueue", DISPATCH_QUEUE_SERIAL), ^{
        NSArray *daysDataArr = [daysDataSource sortedArrayUsingComparator:^NSComparisonResult(NSString * _Nonnull obj1, NSString *_Nonnull obj2) {
            return [obj1 compare:obj2] != NSOrderedAscending;
        }];
        _daysDataSource = daysDataArr;
        NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
        // 处理数据
        for (NSString *dayStr in daysDataSource) {
            NSDate *date = [NSDate formateYearMonthDayString:dayStr];
            NSString *year = @([date year]).stringValue;
            NSString *month = @([date month]).stringValue;
            NSString *day = @([date day]).stringValue;
            if ([dictM.allKeys containsObject:year]) {
                NSMutableDictionary *monthDict = [NSMutableDictionary dictionaryWithDictionary:dictM[year]];
                NSLog(@"monthDict:%@",monthDict);
                if ([monthDict.allKeys containsObject:month]) {
                    NSMutableArray *dayArr = [NSMutableArray arrayWithArray:monthDict[month]];
                    [dayArr addObject:day];
                    NSLog(@"dayArr:%@",dayArr);
                    monthDict[month] = dayArr.copy;
                }else {
                    [monthDict setObject:@[day] forKey:month];
                }
                dictM[year] = monthDict;
            }else {
                [dictM setObject:@{month:@[day]} forKey:year];
            }
        }
        self.yearMonthDayDict = dictM.copy;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.pickerView reloadAllComponents];
        });
    });
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.yearMonthDayDict.allKeys.count;
    }else if (component == 1){
        if (self.currentYear) {
            NSDictionary *dict = [self.yearMonthDayDict objectForKey:self.currentYear];
            return dict.allKeys.count;
        }else{
            NSInteger oneComRow = [pickerView selectedRowInComponent:0];
            NSString *year =[self.yearMonthDayDict.allKeys objectAtIndex:oneComRow];
            NSDictionary *dict = [self.yearMonthDayDict objectForKey:year];
            return dict.allKeys.count;
        }
    }else {
//        if (self.currentMonth && self.currentYear) {
//            NSDictionary *dict = [self.yearMonthDayDict objectForKey:self.currentYear];
//            return [[dict objectForKey:self.currentMonth] count];
//        }else{
//
//        }
        NSInteger oneComRow = [pickerView selectedRowInComponent:0];
        NSString *year =[self.yearMonthDayDict.allKeys objectAtIndex:oneComRow];
        NSDictionary *dict = [self.yearMonthDayDict objectForKey:year];
        NSInteger twoComRow = [pickerView selectedRowInComponent:1];
        NSString *month = [dict.allKeys objectAtIndex:twoComRow];
        return [dict[month] count];
    }
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    
    ((UIView *)[pickerView.subviews objectAtIndex:1]).backgroundColor = [UIColor clearColor];
    UILabel *pickerLabel = (UILabel *)view;
    if (!pickerLabel) {
        pickerLabel = [[UILabel alloc] init];
        UIFont *font = kOpenSansFont(OpenSansExtraBold, 20);
        pickerLabel.font = font;
        pickerLabel.textColor = kTWhiteText;
    }
    NSString *title = @"";
    ((UIView *)[pickerView.subviews objectAtIndex:2]).backgroundColor = [UIColor clearColor];
    if (component == 0) {
        title = self.yearMonthDayDict.allKeys[row];
    }else if (component == 1) {
        if (self.currentYear) {
            NSDictionary *dict = self.yearMonthDayDict[self.currentYear];
            title = [dict.allKeys objectAtIndex:row];
        }else {
            NSInteger oneComRow = [pickerView selectedRowInComponent:0];
            NSString *year =[self.yearMonthDayDict.allKeys objectAtIndex:oneComRow];
            self.currentYear = year;
            NSDictionary *dict = [self.yearMonthDayDict objectForKey:year];
            title = [dict.allKeys objectAtIndex:row];
        }
    }else {
//        if (self.currentMonth && self.currentYear) {
//            NSDictionary *dict = [self.yearMonthDayDict objectForKey:self.currentYear];
//            title = dict[self.currentMonth][row];
//        }
        NSInteger oneComRow = [pickerView selectedRowInComponent:0];
        NSString *year =[self.yearMonthDayDict.allKeys objectAtIndex:oneComRow];
        NSDictionary *dict = [self.yearMonthDayDict objectForKey:year];
        NSInteger twoComRow = [pickerView selectedRowInComponent:1];
        NSString *month = [dict.allKeys objectAtIndex:twoComRow];
        title = dict[month][row];
        
    }
    pickerLabel.text = title;
    [pickerLabel sizeToFit];
    return pickerLabel;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        NSString *year = [self.yearMonthDayDict.allKeys objectAtIndex:row];
        self.currentYear = year;
        [pickerView reloadComponent:1];
        [pickerView reloadComponent:2];
    }else if (component == 1){
        if (self.currentYear) {
            NSDictionary *dict = self.yearMonthDayDict[self.currentYear];
            self.currentMonth = [dict.allKeys objectAtIndex:row];
        }else {
            NSInteger oneComRow = [pickerView selectedRowInComponent:0];
            NSString *year =[self.yearMonthDayDict.allKeys objectAtIndex:oneComRow];
            self.currentYear = year;
            NSDictionary *dict = [self.yearMonthDayDict objectForKey:year];
            self.currentMonth = [dict.allKeys objectAtIndex:row];
        }
        [pickerView reloadComponent:2];
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 48;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    return ((self.bounds.size.width - 60) / 3);
}


@end
